#include "AsioIOServicePool.h"
AsioIOServicePool::AsioIOServicePool(std::size_t size):_ioServices(size),_works(size),_nextIOService(0) {
	for (std::size_t i = 0; i < size; ++i) {
		_works[i] = std::unique_ptr<Work>(new Work(_ioServices[i]));//用右值赋值uniqueptr
	}
	//遍历多个ioservice,创建多个线程,每个线程都启动ioservice
	for (std::size_t i = 0; i < _ioServices.size(); ++i) {
		//快速构造,插入线程容器直接调用thread内部回调函数初始化thread,避免二次构造和多个线程跑的隐患
		//只要创建一个线程,线程就跑起来了
		_threads.emplace_back([this, i]() {//this这里是_ioservices
			_ioServices[i].run();
			});

		//thread t(lambda);
		//_threads.push_back(t);和上面的区别是pushback拷贝了一次,实际上有两个线程,就额外开销了
		//_threads.push_back(move(t));//进行生命周期接管也不太安全,不能保证
	}

}
AsioIOServicePool::~AsioIOServicePool() {
	std::cout << "AsioIOServicePool destruct" << endl;
}
boost::asio::io_context& AsioIOServicePool::GetIOService() {
	auto& service = _ioServices[_nextIOService++];
	if (_nextIOService == _ioServices.size()) {
		_nextIOService = 0;
	}
	return service;
}
void AsioIOServicePool::Stop() {
	for (auto& work : _works) {
		work.reset();//智能指针释放
	}
	for (auto& t : _threads) {
		t.join();//stop()阻塞等待所有线程退出
	}
}